﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour {
	public static GameManager instance;
	public int gold;
	public int waveNumber;
	public int escapedEnemies;
	public int maxAllowedEscapedEnemies=5;
	public bool enemySpawningOver;
	public AudioClip gameWinSound;
	public AudioClip gameLoseSound;

	private bool gameOver;

	void Awake(){
		instance = this;
	}

	
	// Update is called once per frame
	void Update () {
		if(!gameOver&&enemySpawningOver){

			if (EnemyManager.instance.enemies.Count == 0)
			{
				OnGameWin ();
				UIManager.instance.ShowWinScreen ();
			}
		}
		if (Input.GetKeyDown (KeyCode.Escape))
		{
			QuitToTitleScreen ();
		}
	}

	private void OnGameWin(){
		AudioSource.PlayClipAtPoint (gameWinSound,Camera.main.transform.position);
		gameOver = true;
	}

	public void QuitToTitleScreen(){
		SceneManager.LoadScene ("TitleScreen");
	}

	public void OnEnemyEscape(){
		escapedEnemies++;
		UIManager.instance.ShowDamage ();
		if (escapedEnemies == maxAllowedEscapedEnemies)
		{
			OnGameLose ();
			UIManager.instance.ShowLoseScreen ();
		}
	}

	private void OnGameLose(){
		gameOver = true;
		AudioSource.PlayClipAtPoint (gameLoseSound,Camera.main.transform.position);
		EnemyManager.instance.DestroyAllEnemies ();
		WaveManager.Instance.StopSpawning ();
	}

	public void RetryLevel(){
		SceneManager.LoadScene ("Game");
	}

}
